<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" width="800"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="submitHandle()"
             label-width="120px">
      <el-form-item label="食品名称" prop="foodName">
        <el-input v-model="dataForm.foodName" placeholder="食品名称" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="食品热量" prop="foodTrophy">
        <el-input type="number" v-model="dataForm.foodTrophy" placeholder="食品热量" style="width: 400px"></el-input>
      </el-form-item>

      <el-form-item label="食物图标" prop="foodIconUrl">
        <el-upload ref="foodIconUrlRef"
                   class="avatar-uploader"
                   :action="url"
                   list-type="picture-card"
                   :auto-upload="false"
                   :limit="1"
                   :on-preview="handlePictureCardPreview"
                   :before-upload="beforeImageUpload"
                   :on-change="changeImageUpload"
                   :on-success="handUploadSuccess"
                   :on-remove="handUploadRemove"
                   :file-list="foodImages"
                   accept="image/png, image/gif, image/jpg, image/jpeg"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="状态" prop="foodStatus">
        <el-select v-model="dataForm.foodStatus" placeholder="状态 0-不可用 1-可用" style="width: 400px">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input type="number" v-model="dataForm.weight" placeholder="重量" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="脂肪(克)" prop="protein">
        <el-input type="number" v-model="dataForm.protein" placeholder="脂肪(克)" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="蛋白质含量(克)" prop="fat">
        <el-input type="number" v-model="dataForm.fat" placeholder="蛋白质含量(克)" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="碳水化合物(克)" prop="carbohydrates">
        <el-input type="number" v-model="dataForm.carbohydrates" placeholder="碳水化合物(克)" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="起始BMI" prop="startBmi">
        <el-input type="number" v-model="dataForm.startBmi" placeholder="起始BMI" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="结束BMI" prop="endBmi">
        <el-input type="number" v-model="dataForm.endBmi" placeholder="结束BMI" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="有利于疾病" prop="goodIllness">
        <el-select v-model="goodIllness" filterable multiple placeholder="有利于疾病" style="width: 400px">
          <el-option
            v-for="item in illnessOption"
            :key="item.id"
            :label="item.illnessName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="不利于疾病" prop="badIllness">
        <el-select v-model="badIllness" filterable multiple placeholder="不利于疾病" style="width: 400px">
          <el-option
            v-for="item in illnessOption"
            :key="item.id"
            :label="item.illnessName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用时段" prop="planDayTime">
        <el-select v-model="planDayTime" filterable multiple placeholder="适用时段" style="width: 400px">
          <el-option
            v-for="item in planDayTimeOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="食物类型" prop="foodType">
        <el-select v-model="dataForm.foodType" filterable placeholder="食物类型" style="width: 400px">
          <el-option
            v-for="item in foodTypeOpt"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
    <div style="width: 350px">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible">
    <img :src="dialogImageUrl" alt="Preview Image" width="100%"/>
  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, reactive, ref, watch} from "vue";
import baseService from "@/service/baseService";
import {ElMessage, UploadFile, UploadFiles} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import app from "@/constants/app";
import {getToken} from "@/utils/cache";
let props = defineProps(['illnessOption','foodTypeOpt'])
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const foodIconUrlRef = ref() //图片ref
const foodIconUrl = ref() //图片url
const isUpdate = ref(false) // 是否更新功能
const foodIconReady = ref(false) // 是否上传过图片
const foodImages = ref([{name: '', url: ''}]) // 食物图片,用于回显
const goodIllness = ref<Array<string>>([])
const badIllness = ref<Array<string>>([])
const planDayTime = ref<Array<string>>([])

const dataForm = reactive({
  id: '',
  foodName: '',
  foodTrophy: '',
  foodIconUrl: '',
  foodStatus: 1,
  weight: '',
  endBmi: '',
  startBmi: '',
  goodIllness: '',
  badIllness: '',
  planDayTime: '',
  foodType: '',
  protein: '',
  fat: '',
  carbohydrates: '',
  createDate: '',
  updateDate: '',
  creator: '',
  updater: ''
});
const rules = ref({
  foodName: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  foodTrophy: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  foodIconUrl: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  foodStatus: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  weight: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  startBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  endBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  goodIllness: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  badIllness: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  planDayTime: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  foodType: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  protein: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  fat: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  carbohydrates: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
});
const planDayTimeOpt = ref([{key: '1', value: '早'}, {key: '2', value: '中'}, {key: '3', value: '晚'}])
const statusOptions = [
  {
    value: 1,
    label: '可用',
  },
  {
    value: 0,
    label: '不可用',
  }]
const url = ref("");

// 初始化函数
const init = (id?: number) => {
  dataForm.id = "";
  foodImages.value.splice(0,foodImages.value.length)
  goodIllness.value.length = 0
  badIllness.value.length = 0
  planDayTime.value.length = 0
  url.value = `${app.api}/health/food/upload?token=${getToken()}`;
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  nextTick(() => {
    visible.value = true;
  })
  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/health/food/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    if (id) {
      isUpdate.value = true
      foodImages.value = [dataForm.foodIconUrl].map(item => {
        return {
          name: item,
          url: item
        }
      });
      foodIconUrl.value = dataForm.foodIconUrl

      goodIllness.value = dataForm.goodIllness.split(',')
      badIllness.value = dataForm.badIllness.split(',')
      planDayTime.value = dataForm.planDayTime.split(',')
    }
  });
};

// 表单提交
const submitHandle = () => {
  if (!foodIconUrl.value) {
    ElMessage.error("请上传图片");
  }
  if (foodIconReady.value) {
    // 这里上传文件，上传成功自动执行上传成功钩子 handUploadSuccess
    foodIconUrlRef.value.submit()
    foodIconReady.value = false
  } else {
    dataFormSubmit()
  }
};

// 表单数据提交
const dataFormSubmit = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/health/food", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
}

// 图片上传成功
const handUploadSuccess = (res: any) => {
  dataForm.foodIconUrl = res.data.url
  dataFormSubmit()
}

//图片状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeImageUpload = (file: any) => {
  if (file.status === 'ready') {
    foodIconUrl.value = file.url
    foodIconReady.value = true;
    console.log("图片读取")
  }
}

// 图片上传之前
const beforeImageUpload = (file: any) => {
  if (file.size / 1024 / 1024 > 10) {
    ElMessage.error("单张图片大小不能超过10MB!");
    return false;
  }
  return true;
}
// 图片删除
const handUploadRemove = (file: UploadFile, files: UploadFiles) => {
  dataForm.foodIconUrl = '';
}

//图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
defineExpose({
  init
});

watch(() => goodIllness.value ,(val) => {
  dataForm.goodIllness = val.join(',')
})
watch(() => badIllness.value,(val) => {
  dataForm.badIllness = val.join(',')
})
watch(() => planDayTime.value,(val) => {
  dataForm.planDayTime = val.join(',')
})
</script>

<style>
.avatar-uploader {
  width: 150px;
  height: 150px !important;
  overflow: hidden;
}
</style>
